<?php

namespace app\backend\controller;

use app\backend\model\User;
use app\backend\model\Module;
use think\Controller;

class Base extends Controller
{
    public function initialize()
    {

        if (empty(session('username'))) {
            return $this->error(
                '你还未登录,页面将在3秒后自动跳转登录页',
                '/login/index'
            );
        }


        //获取登录用户权限列表
        $nodeList = [];
        $user = User::with('role')->get(session('uid'));
        $nodeIds = $user->role->node;

        $nodes = explode(',', $nodeIds);

        //获取模型信息
        $module = Module::select($nodes);

        foreach ($module as $key => $value) {
            $control = $value->controller;
            $action = $value->action;
            $nodeList['controller'][] = $control;
            $nodeList['url'][] = $control."/".$action;
        }

        //权限检测
        $controller = lcfirst(request()->controller());
        $action = lcfirst(request()->action());

        if (!in_array($controller . '/' . $action, $nodeList['url']))
        {
            return $this->error('你没有权限执行该操作');
        }

    }
}
